'use strict'
import axios from 'axios'
import router from '../router'
import store from '../store'
import QS from 'qs'

const instance = axios.create({})
instance.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
instance.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
instance.defaults.withCredentials = true;
instance.defaults.timeout = 90000;


instance.interceptors.response.use(
    response => {
        if (response.status === 200 || response.status === 304) {
            return response.data;
        }
        return Promise.reject(response.status);
    },
    error => {
        if (!error.response) return
        router.push(`/login`);
        console.log('[ MOCKJS API ERROR ]', error.response.status)
        return Promise.reject(error);
    }
)

/**
 * easy-mock模拟的基本假
 * https://mock.mengxuegu.com/
 */
const mockDefault = '/mock/6098d304c7b7385be0a832b9/autism/'

/**
 * 这里加传了唯一参数 防止判定重复调用
 * @param {地址} url 
 * @returns 
 */
export const postOnly = url => {
    return async data => {
        return (await instance.post(
            `${ mockDefault }${url}`,
            {
                ...data,
                _t: Date.now(),
            },
            {
                paramsSerializer: params => {
                    return QS.stringify(params);
                }
            }
        ));
    }
}


export const postDefault = url => {
    return async data => {
        return (await instance.post(
            `${ mockDefault }${url}`,
            data,
            {
                paramsSerializer: params => {
                    return QS.stringify(params);
                }
            }
        ));
    }
}


export const postForm = url => {
    return async data => {
        return (await instance({
            method: 'post',
            url: `${ mockDefault }${url}`,
            data,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            paramsSerializer: params => {
                return QS.stringify(params);
            }
        }));
    }
}


export const get = url => {
    return async data => {
        return (await instance.get(
            `${ mockDefault }${url}`,
            {
                params: {
                    ...data,
                    _t: Date.now(),
                }
            }
        ));
    }
}

export const customInstance = instance;